const Service = require("egg").Service;
const errorLog = require("../utils/errorLog");

// roleId为2是作为删除的角色，不可删除

class RoleService extends Service {
  async getRoleById(id) {
    try {
      const role = await this.app.model.RoleModel.findOne({
        where: { id, isShow: 1 },
        // include: [
        //   {
        //     model: this.app.model.MenuModel,
        //     as: "menu", // 根据你的关联定义
        //   },
        // ],
      });
      return role;
    } catch (err) {
      errorLog("RoleService----->getRoleById", err);
      return false;
    }
  }

  async getRoleMenuByRoleId(roleId) {
    try {
      const role = await this.app.model.RoleMenu.findAll({
        where: { roleId },
      });
      return role;
    } catch (err) {
      errorLog("RoleService----->getRoleMenuByRoleId", err);
      return false;
    }
  }

  async getRoleList(currentPage, pageSize) {
    try {
      const offset = (currentPage - 1) * parseInt(pageSize);
      const roleList = await this.app.model.RoleModel.findAll({
        where: { isShow: 1 },
        offset: offset,
        limit: parseInt(pageSize),
      });
      return roleList;
    } catch (err) {
      errorLog("RoleService----->getRoleList", err);
      return false;
    }
  }

  async getAllRole() {
    try {
      const roleList = await this.app.model.RoleModel.findAll({
        where: { isShow: 1 },
      });
      return roleList;
    } catch (err) {
      errorLog("RoleService----->getAllRole", err);
      return false;
    }
  }

  async createRole(roleObj) {
    try {
      roleObj.createAt = Date.now();
      roleObj.updateAt = Date.now();
      roleObj.isShow = 1;
      const role = await this.app.model.RoleModel.create(roleObj);
      return role;
    } catch (err) {
      errorLog("RoleService----->createRole", err);
      return false;
    }
  }

  async updateRole(roleObj) {
    try {
      if (
        (roleObj.roleName.length === 0 && roleObj.roleCode.length === 0) ||
        roleObj.id === 2
      )
        return false;
      roleObj.updateAt = Date.now();
      const role = await this.app.model.RoleModel.update(roleObj, {
        where: { id: roleObj.id },
      });
      return role;
    } catch (err) {
      errorLog("RoleService----->updateRole", err);
      return false;
    }
  }

  async deleteRole(id, options = {}) {
    try {
      if (id == 2 || id == 3) return false;
      const { transaction } = options;
      const result = await this.app.model.RoleModel.destroy({
        where: { id },
        transaction,
      });
      return result > 0;
    } catch (err) {
      errorLog("RoleService----->deleteRole", err);
      throw err;
    }
  }
}

module.exports = RoleService;
